package com.xmotor.test_request_response_api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

@Controller
@RequestMapping("/test_request_response_api")
public class TestRequestResponseApiController {

    // localhost:8090/test_context_path/test_request_response_api/test1?id=2&name=Tom
    @ResponseBody
    @RequestMapping("/test1")
    public void test1(HttpServletRequest request, HttpServletResponse response){
        System.out.println("getContextPath:"+request.getContextPath());
        System.out.println("getQueryString:"+request.getQueryString());
        System.out.println("getRequestURI:"+request.getRequestURI());
        System.out.println("getServletPath:"+request.getServletPath());
        System.out.println("getHeader:"+request.getHeader("Host"));
        System.out.println("getCookies:"+request.getCookies());
        response.addCookie(new Cookie("test_cookie","aaa"));
        response.setHeader("test_token","bbb");
    }

    // 测试获取请求体中的json格式的数据（正常是通过@RequestBody注解接收）
    // localhost:8090/test_context_path/test_request_response_api/test2
    // {
    //    "id":100,
    //    "name":"Tom",
    //    "age":18
    // }
    @ResponseBody
    @RequestMapping(value = "/test2",method = RequestMethod.POST)
    public void test2(HttpServletRequest request) throws IOException {
        JSONObject obj = JSON.parseObject(request.getInputStream(), Charset.forName("UTF-8"),JSONObject.class);
        System.out.println(obj);
    }

    @ResponseBody
    @RequestMapping("/test3")
    public void test3(HttpServletRequest request) throws Exception{
        String pageUrl = request.getParameter("pageUrl");
        System.out.println("pageUrl: " + pageUrl);
    }
}
